package com.cml.sqlversionupgradestarter.context;

import com.cml.sqlversionupgradestarter.entity.SqlUpgradeIndex;
import com.cml.sqlversionupgradestarter.entity.SqlUpgradeVersion;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：陈茂林
 * 时间：2022/1/6
 * 描述：
 */
public class SqlUpgradeMetadataContext {

    private List<SqlUpgradeIndex> sqlUpgradeIndexList = new ArrayList<SqlUpgradeIndex>();

    private Map<String, List<SqlUpgradeVersion>> sqlUpgradeContextMap=new HashMap<String, List<SqlUpgradeVersion>>();


    public void addSqlUpgradeIndex(SqlUpgradeIndex sqlUpgradeIndex){
        this.sqlUpgradeIndexList.add(sqlUpgradeIndex);
    }

    public void addSqlUpgradeContext(String fileName,SqlUpgradeVersion sqlUpgradeVersion){
        if(this.sqlUpgradeContextMap.get(fileName) == null){
            this.sqlUpgradeContextMap.put(fileName,new ArrayList());
        }
        this.sqlUpgradeContextMap.get(fileName).add(sqlUpgradeVersion);
    }

    public void sqlUpgradeContextBuild(){
        sqlUpgradeContextMap.forEach((fileName,sqlUpgradeVersionList)->{//遍历所有sql文件
            sqlUpgradeIndexList.forEach(sqlUpgradeIndex -> {//把sql语句组装到索引文件中
                if(fileName.equals(sqlUpgradeIndex.getSqlUpgradeVersionFileName())){
                    sqlUpgradeVersionList.forEach(sqlUpgradeVersion->{
                        if(sqlUpgradeIndex.getDate().compareTo(sqlUpgradeVersion.getVerDate())==0){
                            sqlUpgradeIndex.setSqlUpgradeVersion(sqlUpgradeVersion);
                        }
                    });
                }

            });
        });


    }

    public List<SqlUpgradeIndex> getSqlUpgradeIndexList(){
        return this.sqlUpgradeIndexList;
    }
}
